package top.lingchen.bootwebadmin.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author 凌宸
 * @create 2021-12-08 下午 9:23
 * @Description
 * @Version 1.0
 */
@Slf4j
@Controller
public class FormController {
    @GetMapping("/form_layouts")
    public String formLayouts(){
        return "form/form_layouts";
    }

    /**
     * MultipartFile 自动封装上传的文件
     * @param email
     * @param userName
     * @param headerImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("userName") String userName,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
        log.info("上传的信息：email：" + email + "\t userName:" + userName);
        log.info("上传的信息：headerImg.getSize()：" + headerImg.getSize() + "\t photos.length:" + photos.length);
        String path = "D:\\LearningMaterials\\SpringBoot2\\learningspringboot2\\boot-web-admin\\src\\main\\resources\\upload\\";
        // 上传的文件不为空时，将其保存在项目指定位置
        System.out.println(path);
        if(!headerImg.isEmpty()){
            String originalFilename = headerImg.getOriginalFilename();
            headerImg.transferTo(new File(path + originalFilename));
        }
        if(photos.length > 0){
            for (MultipartFile photo : photos){
                if(!photo.isEmpty()){
                    String originalFilename = photo.getOriginalFilename();
                    photo.transferTo(new File(path + originalFilename));
                }
            }
        }
        return "main";
    }

}
